package com.bcx.crm.spring_boot.springMVC.controllerAdvice;

import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * Created by ys on 2018/4/22.
 * 1.针对控制器(@Controller)的全局配置,@Controller声明一个控制器建言
 * 2.定义全局处理,value为异常的拦截条件,此处为拦截所有的Exception
 * 3.@ModelAttribute注解将键值对添加到全局,所有带有@RequestMapping注解的方法均可获得此键值对,
 *    也就是说此注解执行于目标方法之前
 * 4.通过@InitBinder 注解定制 WebDataBinder
 *   4.1演示忽略request参数的id
 */
@ControllerAdvice   //1.
public class ExceptionHandlerAdvice {
    @ExceptionHandler(value = Exception.class)  //2.
    public ModelAndView exception(Exception exception, WebRequest webRequest){
        ModelAndView modelAndView = new ModelAndView("crm/public/error"); //error页面
        modelAndView.addObject("errorMessage",exception.getMessage());
        modelAndView.addObject("allErrorMessage","系统内部出现异常,请联系管理员");
        return modelAndView;
    }
    @ModelAttribute
    public void addAttributes(Model model){     //3.
        model.addAttribute("msg","额外信息");
    }
    @InitBinder     //4.
    public void initBinder(WebDataBinder webDataBinder){
        webDataBinder.setDisallowedFields("id");    //4.1
    }

}
